package ua.net.gm.server.walker.dummy;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Random;
import ua.net.gm.server.walker.IWalker;
import ua.net.gm.server.walker.IWalkerMove;
import ua.net.gm.server.walker.IWalkerMovesEstimator;
import ua.net.gm.server.walker.IWalkerMovesFactory;
import ua.net.gm.server.walker.WalkerMoveRank;
import ua.net.gm.server.walker.WalkerStrategy;

/**
 *
 * @author Yason
 */
public class RandomMoveStrategy extends WalkerStrategy
{
    private final Random rnd = new Random();
    
    public RandomMoveStrategy(IWalkerMovesFactory factory, IWalkerMovesEstimator estimator)
    {
        super(factory, estimator);
    }

    @Override
    protected IWalkerMove chooseMove(IWalker state, Map<WalkerMoveRank, IWalkerMove> moves)
    {
        List<WalkerMoveRank> ranks = new ArrayList<>(moves.keySet());
        Collections.sort(ranks);
        
        int n = 0;
        int sum = 0;
        int[] weight = new int[ranks.size()];
        for (WalkerMoveRank rank : ranks)
        {
            sum += rank.getRank();
            weight[n] = sum;
            n++;
        }
        int r = rnd.nextInt(sum);
        for (int i = 0; i < weight.length; i++)
        {
            if (r < weight[i])
            {
                break;
            }
        }
        return moves.get(ranks.get(n));
    }
}
